package com.example.firstprojectnew.utiil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * @Author: lihua
 * @Date: 2025/4/23 15:53
 * @Version: v1.0.0
 * @Description:
 **/
public class JwtUtil {

    private static final long EXPIRATION_TIME = 86400000; // 1天的过期时间
    public static final String HEADER = "Authorization";

    // 生成 JWT Token
    public static String generateToken(String username, Map<String,Object> info) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 10*60*1000))
                .signWith(SignatureAlgorithm.HS256, "test")
                .addClaims(info)
                .compact();
    }

    // 解析 JWT Token
    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey("test")
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            return null; // token无效
        }
    }

    // 获取用户名
    public static String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.getSubject() : null;
    }

    // 验证 Token 是否过期
    public static boolean isTokenExpired(String token) {
        Claims claims = parseToken(token);
        return claims != null && claims.getExpiration().after(new Date());
    }
}
